package com.csc.banking.dao;

import java.util.List;

import javax.persistence.Query;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TransactionRequiredException;



import com.csc.banking.model.EntityObject;


public abstract class GenaricDao 
{
	@PersistenceContext protected EntityManager em;
	
	Class<?> getEntityClass()
	{
		return Object.class;
	}
	
	public Integer count()
	{
		StringBuffer queryString = new StringBuffer("select count(g) from " + getEntityClass().getSimpleName()+" g");
		Query query = this.em.createQuery(queryString.toString());
		  return (Integer)query.getSingleResult();
	}
	
	public EntityObject getOne(Object primaryKey)
	{
		EntityObject res=null;
		res = (EntityObject) em.find(getEntityClass(), primaryKey);
		return res;//may be null
	}
	
	public int insert(EntityObject arg)
	{
		
		int res=0;
		try
		{
			em.persist(arg);
			res=1;
		}
		catch(EntityExistsException e)
		{
			e.printStackTrace();
		}
		catch(TransactionRequiredException e)
		{
			e.printStackTrace();
		}
		catch(IllegalArgumentException e)
		{
			e.printStackTrace();
		}
		return res;
    }
	

	public List<EntityObject> getAll() 
	{
    	Query query = em.createQuery("SELECT g FROM " + getEntityClass().getSimpleName()+" g");
    	  return query.getResultList();
    }
	
	
	
	public int update(EntityObject arg)
	{
		int res=0;
		try
		{
			em.merge(arg);
			res=1;
		}
		catch(IllegalArgumentException e)
		{
			e.printStackTrace();
		}
		catch(TransactionRequiredException e)
		{
			e.printStackTrace();
		}
		return res;
	}
	
	
	public int delete(EntityObject arg)
	{
		int res=0;
		try
		{
			em.remove(em.contains(arg) ? arg : em.merge(arg));
			res=1;			
		}		
		catch(IllegalArgumentException e)
		{
			e.printStackTrace();
		}
		catch(TransactionRequiredException e)
		{
			e.printStackTrace();
		}
		return res;		
    }
}
